package com.ph.base;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.ph.constant.ImgConstant;
import com.ph.util.ResultUtil;

@ControllerAdvice
public class BaseErrorController {
	
	private static final Logger logger = LoggerFactory.getLogger(BaseErrorController.class);
	
	/**
	 * @Title: defaultErrorHandler   
	 * @Description: 500异常处理 
	 * @param: @param request
	 * @param: @param e
	 * @param: @param model
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@ExceptionHandler(value = Exception.class)
	public String defaultErrorHandler(HttpServletRequest request, Exception e,Model model){
		logger.error("BaseErrorController Exception >> ",e);
		logger.error("request error url >> ",request.getRequestURL());
		model.addAttribute("code", 500);
		model.addAttribute("msg", "非常抱歉，系统发生错误");
		return "error/500";

	}
	
	/**
	 * @Title: pageNoFoundHandler   
	 * @Description: 404异常处理   
	 * @param: @param request
	 * @param: @param exception
	 * @param: @param model
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@ExceptionHandler(value = NoHandlerFoundException.class)
	public String pageNoFoundHandler(HttpServletRequest request,NoHandlerFoundException exception, Model model){
		logger.error("BaseErrorController NoHandlerFoundException >> ",exception);
		logger.error("request error url >> ",request.getRequestURL());
		model.addAttribute("code", 404);
		model.addAttribute("msg", "您访问的页面暂时找不到了，有可能链接错误或者网络问题");
		return "error/404";
	}
	/**
	 * 
	 * @Title: multipartException   
	 * @Description: 文件上传错误 返回
	 * @param: @param request
	 * @param: @param exception
	 * @param: @return      
	 * @return: Map<String,Object>      
	 * @throws
	 */
	@ResponseBody
	@ExceptionHandler(value = org.springframework.web.multipart.MultipartException.class)
	public Map<String, Object> multipartException(HttpServletRequest request,
			org.springframework.web.multipart.MultipartException exception) {
		Map<String, Object> map = ResultUtil.setResult(false,
				"文件上传失败，请检查文件是否格式是否正确，或文件大小是否超过 " + ImgConstant.MAX_SISE / 1024 / 1024 + "M");
		logger.error("BaseErrorController MultipartException >> ", exception);
		return map;
	}
}
